package translinkApp.Data.Parse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.content.Context;

public class Poster {

	public String getData(Context c, String urlString, ArrayList<KeyPair> params)
			throws IOException {

		// Construct data
		String data = "";
		boolean firstLoopDone = false;
		for (KeyPair key : params) {
			if (firstLoopDone) {
				data += "&";
			} else {
				firstLoopDone = true;
			}
			data += URLEncoder.encode(key.getKey(), "UTF-8") + "="
					+ URLEncoder.encode(key.getValue(), "UTF-8");
		}

		// Send data
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		// String userAgent = new WebView(c).getSettings().getUserAgentString();
		conn.setDoOutput(true);
		conn.setRequestProperty(
				"User-Agent",
				// "Mozilla/5.0 (Linux; U; Android 0.5; en-us) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3"
				"Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3");
		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(data);
		wr.flush();

		// Get the response
		return inputStreamToString(conn.getInputStream());
	}

	private static String inputStreamToString(InputStream is) throws IOException {

		BufferedReader r = new BufferedReader(new InputStreamReader(is));
		StringBuilder total = new StringBuilder();
		String line;
		while ((line = r.readLine()) != null) {
			total.append(line);
		}

		return total.toString();
	}

}
